package photorganizer.presentation.common.action;

import java.awt.event.ActionEvent;
import java.lang.reflect.Method;

import photorganizer.common.exception.TechnicalException;

public class ReflectAction extends SimpleAction {

	private static final long serialVersionUID = 4175553387535965106L;

	private Object handler;

	private Method method;

	private boolean eventParameter;

	public ReflectAction(Object handler, String command) {
		super(command);
		this.handler = handler;

		for (Method method : handler.getClass().getDeclaredMethods()) {
			ActionImpl callback = method.getAnnotation(ActionImpl.class);
			if (callback != null && command.equals(callback.value())) {
				this.method = method;
				method.setAccessible(true);
				Class<?>[] parameterTypes = method.getParameterTypes();
				eventParameter = parameterTypes.length == 1 && ActionEvent.class.equals(parameterTypes[0]);
				return;
			}
		}

		// TODO gestion exception
		assert false;
	}

	@Override
	public void actionPerformed(ActionEvent event) {
		try {
			if (eventParameter) {
				method.invoke(handler, event);
			}
			else {
				method.invoke(handler);
			}
		}
		catch (Throwable throwable) {
			// TODO gestion exception
			throw new TechnicalException(throwable);
		}
	}

}
